package com.cop4331.social;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Uploads image to apache server
 * 
 */
public class ImageuploadActivity extends Activity {

	private static final int PICK_IMAGE = 1;

	public static String ip = UserFunctions.getIp();

	// EditText Fields
	private EditText caption;

	// Bitmap
	private Bitmap bitmap;

	// Buttons
	private Button finish;
	private Button upload;
	private Button rotate;

	// Stores file name
	private String file1;

	public ImageView preview;
	InputStream inputStream;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.imageupload);

		// EditText
		caption = (EditText) findViewById(R.id.Caption);

		// Buttons
		upload = (Button) findViewById(R.id.Upload);
		finish = (Button) findViewById(R.id.Finish);
		rotate = (Button) findViewById(R.id.rotate);

		// ImageView
		preview = (ImageView) findViewById(R.id.imageView);
		
		// Do not show rotate button till image selected
		rotate.setVisibility(View.GONE);

		// Set functionality to "Upload" button
		// Upload sends selected bitmap image to Apache server stored in
		// http://97.104.23.63/android/profilepictures/
		upload.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// No Image Selected
				if (bitmap == null) {
					Toast.makeText(getApplicationContext(),
							"Please select image", Toast.LENGTH_SHORT).show();
				}

				else {
					// Store user name to be used in next activity
					Bundle b = getIntent().getExtras();

					upload.setText("Upload Complete");

					// Setup the bitmap to be transferred
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); // compress
																			// to
																			// which
																			// format
																			// you
																			// want.
					byte[] byte_arr = stream.toByteArray();
					String image_str = Base64.encodeBytes(byte_arr);
					ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

					// Store image (in string form) and username
					nameValuePairs.add(new BasicNameValuePair("image",
							image_str));
					nameValuePairs.add(new BasicNameValuePair("un", b
							.getString("username")));

					// Send to server
					try {
						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(ip + "upload.php");
						httppost.setEntity(new UrlEncodedFormEntity(
								nameValuePairs));
						@SuppressWarnings("unused")
						HttpResponse response = httpclient.execute(httppost);

					} catch (Exception e) {
						Toast.makeText(ImageuploadActivity.this,
								"ERROR " + e.getMessage(), Toast.LENGTH_LONG)
								.show();
						System.out.println("Error in http connection "
								+ e.toString());
					}

					UserFunctions userFunction = new UserFunctions();

					// Update database with new file image name.
					// Images are named after users (ex. username: mszoke,
					// profileimgname: mszoke.jpg)
					// If image is not selected, "default.jpg" is chosen
					@SuppressWarnings("unused")
					JSONObject json = userFunction.updateImg(b
							.getString("username"));
				}
			}
		});

		// Set finish button listener
		// Starts login intent
		finish.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Bundle b = getIntent().getExtras();

				Intent log;

				if (b.containsKey("from"))
					log = new Intent(getApplicationContext(),
							ViewProfileActivity.class);

				else
					log = new Intent(getApplicationContext(),
							LoginActivity.class);

				startActivity(log);
				finish();
			}
		});
		
		// Rotate button
		rotate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Matrix matrix = new Matrix();
				matrix.postRotate(-90); // clockwise by 90 degrees
				
				// Allows user to rotate image
				bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
						bitmap.getHeight(), matrix, true);
				
				preview.setImageBitmap(bitmap);
			}
		});
	}

	// -----------------------------------------------
	// ONCREATEOPTIONSMENU
	// When user hits menu on phone
	// -----------------------------------------------
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.imageupload_menu, menu);
		return true;
	}

	// Show options after user selects a menu button
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		// User selects image gallery
		case R.id.ic_menu_gallery:

			try {

				// Show pictures to user
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						PICK_IMAGE);

			} catch (Exception e) {
				Log.e(e.getClass().getName(), e.getMessage(), e);
			}

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	// Executes after startActivityForResult (in menu)
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {

		// Checks to see if User picked an image
		case PICK_IMAGE:

			if (resultCode == Activity.RESULT_OK) {

				// Calculate Path to Image on phone
				Uri selectedImageUri = data.getData();
				String filePath = null;

				try {
					String filemanagerstring = selectedImageUri.getPath();
					String selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown path");
					}

					// Store filepath string
					file1 = filePath;
					File file = new File(file1);
					// Image has been selected, print to user
					caption.setText("[Image Selected]");
					
					BitmapFactory.Options options=new BitmapFactory.Options();
					options.inSampleSize = 8;
					
					// Decode file1 into bitmap format
					bitmap = this.decodeFile(file);

					/*Matrix matrix = new Matrix();
					matrix.postRotate(-90); // clockwise by 90 degrees

					Bitmap rotatedBitmap = Bitmap
							.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
									bitmap.getHeight(), matrix, true);*/
					
					/*
					if ((bitmap.getWidth() % 4 == 0) && (bitmap.getHeight() % 3 == 0)){
						bitmap = Bitmap.createScaledBitmap(rotatedBitmap, 150,
								200, true);
						System.out.println(bitmap.getHeight() + " " + bitmap.getWidth() + "3:4");
					}
					else if ((bitmap.getWidth() % 3 == 0) && (bitmap.getHeight() % 4 == 0)){
						System.out.println(bitmap.getHeight() + " " + bitmap.getWidth() + "4:3");
						bitmap = Bitmap.createScaledBitmap(rotatedBitmap, 200, 150, true);
					}
					else{
						
						while ((bitmap.getHeight() > 200) && (bitmap.getWidth() > 200)){
							
							System.out.println(bitmap.getHeight() + " " + bitmap.getWidth());
							
							bitmap = Bitmap.createScaledBitmap(rotatedBitmap, bitmap.getHeight()/2,
									bitmap.getWidth()/2, true);
						}
					}*/
					
					while ((bitmap.getHeight() > 200) && (bitmap.getWidth() > 200)){
						
						System.out.println(bitmap.getHeight() + " " + bitmap.getWidth());
						
						bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth()/2,
								bitmap.getHeight()/2, true);
					}
					
					preview.setImageBitmap(bitmap);
					rotate.setVisibility(View.VISIBLE);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}
			break;
		default:
		}
	}

	// -----------------------------------------------
	// GETPATH
	// Returns selected image path (from SD CARD)
	// -----------------------------------------------
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {

			// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else
			return null;
	}
	
	public void onDestroy(){
		super.onDestroy();
		
		if (bitmap != null)
			bitmap.recycle();
		System.gc();
	}
	

	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation
	
		Matrix matrix = new Matrix();
	
		// resize the bit map
	
		matrix.postScale(scaleWidth, scaleHeight);
	
		// recreate the new Bitmap
	
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
	
		return resizedBitmap;

	}
	
	//decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f){
	    try {
	        //Decode image size
	        BitmapFactory.Options o = new BitmapFactory.Options();
	        o.inJustDecodeBounds = true;
	        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

	        //The new size we want to scale to
	        final int REQUIRED_SIZE=70;

	        //Find the correct scale value. It should be the power of 2.
	        int scale=1;
	        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
	            scale*=2;
	        
	        scale = 4;

	        //Decode with inSampleSize
	        BitmapFactory.Options o2 = new BitmapFactory.Options();
	        o2.inSampleSize=scale;
	        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	    } catch (FileNotFoundException e) {}
	    return null;
	}


}